<template>
  <view class="mz-upload" @click="handleChooseImage">
    <uni-icons v-if="!src" type="plusempty" size="30" color="#999"></uni-icons>
    <image v-if="src" :src="src|formatFilePath" mode="aspectFill" class="upload-image" />
  </view>
</template>

<script>
import { UPLOAD_PATH } from "../../../config/index";
export default {
  props: {
    file: {
      type: String,
      default: () => ""
    },
    formData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      src: this.file
    };
  },
  watch: {
    file(val) {
      // console.log("file", val);

      this.src = this.file;
    }
  },
  methods: {
    handleChooseImage() {
      uni.chooseImage({
        success: chooseImageRes => {
          uni.showLoading();
          const tempFilePaths = chooseImageRes.tempFilePaths;
          uni.uploadFile({
            url: UPLOAD_PATH,
            filePath: tempFilePaths[0],
            name: "file",
            formData: {
              ...this.formData
            },
            success: uploadFileRes => {
              let res = JSON.parse(uploadFileRes.data);
              this.src = res.data[0];
              this.$emit("success", res);
            },
            complete: () => {
              uni.hideLoading();
            }
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
$height: 150rpx;
.mz-upload {
  display: inline-block;
  height: $height;
  width: $height;
  line-height: $height;
  text-align: center;
  // vertical-align: middle;
  border: 1px solid #999;
  color: #999;
  .upload-image {
    height: 100%;
    width: 100%;
  }
}
</style>
